package org.example.nio_demo;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @ClassName DemoBlockimgNIO1
 * @Description
 * @Author zhangsw
 * @Date 2020/11/14 9:50
 * @Version 1.0
 */
public class DemoBlockingNIO1 {

    @Test
    public void client() throws IOException {
        //获取通道
        SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
        //读取本地文件
        FileChannel inChannel = FileChannel.open(Paths.get("D:\\Users\\zhangsw\\Desktop\\work\\S70603-12241603.mp4"), StandardOpenOption.READ);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //读取本地文件
        while ((inChannel.read(buffer)) != -1) {
            buffer.flip();
            sChannel.write(buffer);
            buffer.clear();
        }

        //关闭通道
        inChannel.close();
        sChannel.close();
    }

    @Test
    public void server() throws IOException {
        //获取通道
        ServerSocketChannel ssChannel = ServerSocketChannel.open();
        FileChannel outChannel = FileChannel.open(Paths.get("D:\\Users\\zhangsw\\Desktop\\work\\socket1.mp4"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        //绑定连接
        ssChannel.bind(new InetSocketAddress(9898));
        //获取客户端连接的通道
        SocketChannel sChannel = ssChannel.accept();
        //分配缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //接收客户端数据，保存到本地
        while ((sChannel.read(buffer)) != -1) {
            buffer.flip();
            outChannel.write(buffer);
            buffer.clear();
        }
        //关闭通道
        sChannel.close();
        outChannel.close();
        ssChannel.close();
    }
}
